package com.example.testdownload;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import com.coe3.data.DataStorage;
import com.coe3.data.Information;
import com.coe3.datahandler.BaseActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;

public class AppDownloadAsync extends AsyncTask<String, String, String>  {
	
	private BaseActivity activity = null;
	private String filePath = null;
	private WakeLock wl = null;
	
	public AppDownloadAsync( BaseActivity activity ) {
		this.activity = activity;
	}
	
    @SuppressWarnings("deprecation")
	@Override
    protected void onPreExecute() {
        super.onPreExecute();
        activity.showDialog( BaseActivity.DIALOG_DOWNLOAD_PROGRESS );
        activity.downloadDialog().setProgress(0);
        
        PowerManager pm = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Download item.");
        wl.acquire();

    }

	@SuppressLint("WorldReadableFiles")
	@Override
    protected String doInBackground( String... aurl ) {
        int count;

        try {
            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.setConnectTimeout(90000);
            conexion.connect();
            Log.e(Information.TAG_DBUG, "conexion.getConnectTimeout(): " + conexion.getConnectTimeout());

            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

            String[] separated = aurl[0].split("/");
            String fileName = separated[separated.length-1];
//            filePath = android.os.Environment.getExternalStorageDirectory()+"/download/"+fileName;
            filePath = fileName;
            
            //Save data path.
            DataStorage.setData(activity, MainActivity.KEY_PATH, fileName);
            Log.d( "chud", "Save file path: " + filePath );
            Log.d( "ANDRO_ASYNC", "Save file path: " + filePath );

            mkdir(activity);
            InputStream input = new BufferedInputStream( url.openStream() );
//            OutputStream output = new FileOutputStream( filePath, true );
            File file = new File(getExternalCacheDir(activity), "xxx");
//			OutputStream output = activity.activity( fileName, activity.MODE_WORLD_READABLE );
            OutputStream output = new FileOutputStream(file);

            byte data[] = new byte[1024];

            long total = 0;
            
            activity.downloadDialog().setMax( lenghtOfFile );

            while ( ( count = input.read(data) ) != -1 ) {
                total += count;
                publishProgress( "" + total );
                output.write( data, 0, count );
            }

            output.flush();
            output.close();

            input.close();
        } catch (Exception e) {
        	e.printStackTrace();
        	Log.e(Information.TAG_DBUG, e.getMessage());
        }
        return null;
        
    }
    
    public void mkdir(Context context) throws IOException {

        File file = new File(getExternalCacheDir(context));
        
        if (!file.exists() || !file.isDirectory())
        	Log.d("chud", "file.mkdir(): " + file.mkdirs());
    }
    
    public static String getExternalCacheDir(Context context) {
        final String cacheDir = "/Android/data/" 
        						+ context.getPackageName() 
        						+ "/cache/" 
        						+ "000"
        						+ File.separator;
        return Environment.getExternalStorageDirectory().getPath() + cacheDir;
    }

    @SuppressWarnings("deprecation")
	@Override
    protected void onPostExecute(String unused) {
    	wl.release();
    	wl = null;

    	activity.dismissDialog( BaseActivity.DIALOG_DOWNLOAD_PROGRESS );
    	
    	String path = DataStorage.getData(activity, MainActivity.KEY_PATH, null);
		Log.d("chud", "onPostExecute filePath path: " + path);
		Log.d("chud", "onPostExecute Data_Storage path: " + path);
		
		if(filePath != null)
		{
			((MainActivity) activity).onDownloadDidFinish(activity, filePath );
		}else {
			((MainActivity) activity).onDownloadDidFinish(activity, filePath );
		}//end if
    }
    
    @Override
    protected void onProgressUpdate(String... progress) {
        int total = Integer.parseInt(progress[0]);
        activity.downloadDialog().setProgress(total);
    }
    
    @SuppressWarnings("deprecation")
	@Override
    protected void onCancelled() {
    	// TODO Auto-generated method stub
    	super.onCancelled();
    	wl.release();
    	wl = null;
    	
    	activity.dismissDialog( BaseActivity.DIALOG_DOWNLOAD_PROGRESS );
    	
    	String path = DataStorage.getData(activity, MainActivity.KEY_PATH, null);
		Log.d("chud", "onPostExecute filePath path: " + path);
		Log.d("chud", "onPostExecute Data_Storage path: " + path);
		
		if(filePath != null)
		{
			((MainActivity) activity).onDownloadDidFinish(activity, filePath );
		}else {
			((MainActivity) activity).onDownloadDidFinish(activity, filePath );
		}//end if
    }
    
}
